import handdetectMod as htm
import cv2
import time
import autopy
import numpy as np

cap = cv2.VideoCapture(0)
time1 = 0
handdetect = htm.HandDetector()

Wscreen , Hscreen = autopy.screen.size()
wCam , hCam = 640,480

smoothing = 5
frame = 50
print(Wscreen, Hscreen)

while True:
    success, img = cap.read()

    #1.找到手部位置信息
    # 调用封装的函数
    img, position_list = handdetect.findhands(img, draw=False)
    #2.标定指定的的手指
    if (len(position_list) != 0):
        x1 , y1 = position_list[8][1:]
        x2 , y2 = position_list[12][1:]
        cv2.rectangle(img,(frame,frame),(wCam-frame,hCam-frame),(255,0,255),2)

    #3.检测哪些手指是伸开的
        fingers = handdetect.findfingerUP()
        #print(fingers)
        #4.当只有食指是伸开的时候我们去移动鼠标
        if fingers[1] == 1 and fingers[2] == 0 and fingers[3] == 0 and fingers[4] == 0:
            x3 = np.interp(x1, (frame, wCam - frame), (0, Wscreen))
            y3 = np.interp(y1, (frame, hCam - frame), (0, Hscreen))

            # 5. Move Mouse
            autopy.mouse.move(Wscreen - x3, y3)
            cv2.circle(img, (x1, y1), 15, (255, 0, 255), cv2.FILLED)

    #6.当食指和中指都伸开的时候，click
        if fingers[1] == 1 and fingers[2] == 1 and fingers[3] == 0 and fingers[4] == 0:
            distance ,img = handdetect.finddistance(8,12,img)
            if distance < 30:
                x_center , y_center = (x1+x2) // 2, (y1 + y2)//2
                cv2.circle(img,(x_center,y_center),15,(255, 0, 255), cv2.FILLED)
                autopy.mouse.click(None)

    #7.当食指和小拇指伸开的时候 执行右键的操作
        if fingers[1] == 1 and fingers[2] == 0 and fingers[3] == 0 and fingers[4] == 1:
                autopy.mouse.click(autopy.mouse.Button.RIGHT)

    # 设置FPS
    time2 = time.time()
    fps = 1 / (time2 - time1)
    time1 = time2
    cv2.putText(img, f'FPS : {int(fps)}', (30, 30), cv2.FONT_HERSHEY_PLAIN, 2, (0, 255, 0), 2)

    img = cv2.resize(img,(1024,768))
    cv2.imshow("output", img)
    if cv2.waitKey(1) & 0xff == 27:
        break

cap.release()